package com.gqz.aircraftwar.mvp.model.bomb

import android.graphics.Canvas
import android.graphics.PointF
import com.gqz.aircraftwar.App
import com.gqz.aircraftwar.util.d
import com.gqz.aircraftwar.util.i
import kotlinx.coroutines.*
import java.lang.Exception
import java.util.concurrent.CopyOnWriteArrayList

/**
 * 爆炸管理器
 *
 * @author gqz
 * @data 2020/3/25
 */

class BlastManager private constructor() {
    private val TAG: String = "BlastManager-->"

    private object Holder {
        val instance = BlastManager()
        const val delay = 1000L / 20L
    }

    companion object {
        var instance = Holder.instance
    }

    val ctx = newSingleThreadContext("Blast")
    var job: Job? = null

    var blastList = CopyOnWriteArrayList<Blast>()

    fun start() {
        try {
            job = GlobalScope.launch(ctx) {
                i(TAG, "start--> blastManager worked in ${Thread.currentThread().name}")
                while (App.isRunning) {
//                    d(TAG, "running-->")
                    blastList.filter { it.isPlaying() }.forEach { it.loop() }
                    delay(Holder.delay)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun stop() {
        blastList.clear()
        job?.cancel()
    }

    fun generateBlast(pos: PointF) {
        var blast = blastList.find { !it.isPlaying() && !it.isSmall }
        if (blast == null) {
            blast = Blast(pos.x, pos.y, false)
            blastList.add(blast)
        } else {
            blast.resetPos(pos)
        }
        blast.play()
    }

    fun generateBlastS(pos: PointF) {
        var blast = blastList.find { !it.isPlaying() && it.isSmall }
        if (blast == null) {
            blast = Blast(pos.x, pos.y, true)
            blastList.add(blast)
        } else {
            blast.resetPos(pos)
        }
        blast.play()
    }

    fun drawAll(canvas: Canvas) {
        blastList.filter { it.isPlaying() }.forEach { it.draw(canvas) }
    }

}
